//引入模块
const express = require("express");
const query = require("../util/query.js");
const JWT = require('../util/token.js');

//创建路由器对象
let router = express.Router();

//===============================================
//购物车模块
//================================================
//1.购物车列表 GET /cart/list
//参数:无(获取当前用户的所有记录)
router.get("/list", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  //获取数据:无  
  try {
    //获取当前用户的购物车
    let sql = `select id,product_id ,title,price,count,pic,is_checked from v_shoppingcart_item where user_id = ${user.id} `;
    let result = await query(sql);
				
    let data = result;
    return res.send({ code: 1, msg: `购物车查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message }); 
  }
});


//2.添加购物车 POST /cart/add
// 参数名	       参数说明
// product_id	商品编号
// count 商品数量
router.post("/add", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据 POST请求 从body中获取数据
    let product_id = req.body.product_id;
    if (!product_id) throw new Error("商品编号不能为空");
    
    let count = req.body.count;
    if (!count) throw new Error("商品数量不能为空");

    //判断用户的购物车中是否已有该商品
    let sql = `SELECT id FROM v_shoppingcart_item WHERE user_id=${user.id} AND product_id=${product_id}`;
    
    let result = await query(sql);
    //执行SQL语句 
    if (result.length > 0) {
      //用户购物车已经有该商品，则加count
      sql = `UPDATE lz_shoppingcart_item SET count=count+${count} WHERE user_id=${user.id} AND product_id=${product_id}`;
    } else {
      sql = `INSERT INTO lz_shoppingcart_item(id,user_id,product_id,count,is_checked) VALUES(NULL, ${user.id}, ${product_id}, ${count},1)`;
    }
    // console.log(sql);    
    result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: `添加成功 ` });
    }
    throw new Error("操作失败"); 
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});


//===============================================
//3.删除购物车 GET /cart/delete  
// 参数名	       参数说明
// ids	多个编号(流水号)，用","分割"
router.get("/delete", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据
    let ids = req.query.ids;
    if (!ids) {
      throw new Error("编号（流水号)不能为空");
    }

    //执行SQL语句    
    let sql = `DELETE FROM lz_shoppingcart_item WHERE id in ( ${ids} )`;
    //console.log(sql);

    let result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: `删除成功 ：ids=${ids}` });
    }
    throw new Error("操作失败");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//4.修改购物车项购买数量 GET /updatecount
// 参数名	       参数说明
// id	编号(流水号)
// count 商品数量
router.get("/updatecount", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据
    let id = req.query.id;
    if (!id) throw new Error("编号（流水号)不能为空");
    let count = req.query.count;
    if (undefined == count) throw new Error("商品数量不能为空");
    //执行SQL语句    
    let sql = `UPDATE lz_shoppingcart_item SET count = ${count} WHERE id = ${id} `;
    //console.log(sql);
    let result = await query(sql);//

    //如果数据更改成功，响应行数 > 0
    if (result.affectedRows > 0) {      
      return res.send({ code: 1, msg: `更新成功` }); //响应返回
    }
    throw new Error("操作失败"); 
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//5.购物车项修改是否勾选 GET /updatechecked
// 参数名	   参数说明
// id	编号(流水号)
// is_checked 是否选中 0 | 1
router.get("/updatechecked", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据
    let id = req.query.id;
    if (!id) throw new Error("编号（流水号)不能为空");
    let is_checked = req.query.is_checked; //类型是整数1/0
    //console.log(is_checked)
    //执行SQL语句    
    let sql = `UPDATE lz_shoppingcart_item SET is_checked = ${is_checked} WHERE id = ${id} `;
    //console.log(sql);
    await query(sql);
    let result = await query(sql);//

    //如果数据更改成功，响应行数 > 0
    if (result.affectedRows > 0) {      
      return res.send({ code: 1, msg: `更新成功` }); //响应返回
    }
    throw new Error("操作失败");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//6.购物车列表（勾选商品） GET /listchecked
//参数:无(获取当前用户的所有记录)
router.get("/listchecked", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取当前用户的购物车
    let sql = `select * from v_shoppingcart_item where is_checked = 1 AND user_id = ${user.id} `;
    let result = await query(sql);
    let data = result;
    return res.send({ code: 1, msg: `购物车查询成功`, data });
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//7.清空我的购物车 GET /cart/delete  
// 参数名	       参数说明
// ids	多个编号(流水号)，用","分割"
router.get("/deleteAll", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {   

    //执行SQL语句    
    let sql = `DELETE FROM lz_shoppingcart_item WHERE user_id = ${user.id}`;
    //console.log(sql);

    let result  = await query(sql);
    //如果数据操作成功，响应行数 > 0
    if (result.affectedRows > 0) {
      //响应返回
      return res.send({ code: 1, msg: "删除成功" });
    }
    throw new Error("操作失败或无记录");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});

//===============================================
//8.全选或全不选购物车 GET /updatechecked
// 参数名	   参数说明
// id	编号(流水号)
// is_checked 是否选中 0 | 1
router.get("/updatecheckedAll", async (req, res) => {
  //验证用户Token 请求头中携带Token  req.headers.authorization=
  let user = JWT.getUser(req, res);
  if (user == null) return;  

  try {
    //获取数据,验证数据    
    let is_checked = req.query.is_checked; //类型是整数1/0
    //console.log(is_checked)
    //执行SQL语句    
    let sql = `UPDATE lz_shoppingcart_item SET is_checked = ${is_checked} WHERE user_id = ${user.id} `;
    //console.log(sql);
    await query(sql);
    let result = await query(sql);//

    //如果数据更改成功，响应行数 > 0
    if (result.affectedRows > 0) {      
      return res.send({ code: 1, msg: "更新成功" }); //响应返回
    }
    throw new Error("操作失败或无记录");   
  } catch (error) {
    res.send({ code: -1, msg: error.message });
  }
});
//===============================================
module.exports = router;
